package com.glodon.paas.monitor.server.exception;

/**
 * 监控服务异常处理
 * 
 * @author achun 2013-2-19 下午5:40:30
 */
public class ThrowableUtil {

	/**
	 * 精简异常的堆栈信息(异常链上每个异常保留最近两行堆栈信息）
	 * 
	 * @param ex
	 */
	public static MonitorException clearStackTrace(Throwable ex) {
		if (ex instanceof MonitorException) {
			ex = new MonitorException(((MonitorException) ex).getErrorCode(),
					"Remote service exception.See caused Exception to get more info,please!", ex);
		} else {
			ex = new MonitorException(MonitorException.ErrorCode.UNKNOW_ERROR,
					"Remote service exception.See caused Exception to get more info,please!", ex);
		}
		Throwable ta = ex;
		while (null != ta) {
			StackTraceElement[] st = ta.getStackTrace();
			int stLen = st.length;
			if (stLen > 2) {
				stLen = 2;
			}

			StackTraceElement[] newSt = new StackTraceElement[stLen];
			for (int i = 0; i < stLen; i++) {
				newSt[i] = st[i];
			}
			ta.setStackTrace(newSt);
			ta = ta.getCause();
		}
		return (MonitorException) ex;
	}

	/**
	 * 完全去除异常的堆栈信息，用于dwr调用时减少异常的堆栈传输代价,并且统一为MonitorException，保留errorcode和message<br>
	 * 否则如果客户端没有此异常类的类信息，会出现客户端反序列化异常。
	 * 
	 * @param ex
	 */
	public static MonitorException convertTpException(Throwable ex) {
		if (ex.getClass().equals(MonitorException.class)) {
			// do nothing;
		} else if (ex instanceof MonitorException) {
			ex = new MonitorException(((MonitorException) ex).getErrorCode(), ex.getMessage());
		} else {
			ex = new MonitorException(MonitorException.ErrorCode.UNKNOW_ERROR, ex.getMessage());
		}
		StackTraceElement[] newSt = new StackTraceElement[0];
		ex.setStackTrace(newSt);
		return (MonitorException) ex;
	}
}
